/*
 * 数据持久化模块
 *
 * 以多态的形式组织信息持久化的方式
 *
 **/

#pragma once

#include "util.hh"
#include "conf.hh"
#include "info.hh"

namespace cloud
{

class persist
{
public:
    using ptr = std::shared_ptr<persist>;
    using infos = std::vector<backup_info>;

    virtual ~persist() {}

public:
    virtual void store(const infos&) = 0;
    virtual infos load() = 0;
};

class file_persist : public persist
{
public:
    file_persist() 
        : _record(config::instance().record_file())
    {}

    virtual void store(const infos& infov) override
    {
        util::json js;
        for (auto& info : infov)
            js.append(info.parser_to_json());

        if (!_record.exists())
            _record.create();

        _record.write(js.serialize());
    }

    virtual infos load() override
    {
        util::json js;
        if (!_record.exists() || _record.size() == 0)
        {
            _record.create();
            return {};
        }

        js.deserialize(_record.read());

        infos infov;

        for (size_t i = 0; i < js.size(); ++i)
        {
            infov.push_back(backup_info(js[i]));
        }

        return infov;
    }
private:
    util::file _record;
};

struct persist_factory
{
    template<class persist_type, class... Args>
    static persist::ptr create(Args&&... args)
    {
        return std::make_shared<persist_type>(std::forward<Args>(args)...);
    }
};

}

